<?php
namespace Admin\Controller;
use Common\Controller\CommonController;
class AiController extends CommonController
{
    const cookie_key = 'ADSSFDFGFGHHJHJKR%ERD';

    function _initialize()
    {

        error_reporting(0);  
        // parent::_initialize();
        if ((CONTROLLER_NAME == 'Admin' && ACTION_NAME == 'login') || (CONTROLLER_NAME == 'TicketReport' && ACTION_NAME == 'login') || CONTROLLER_NAME == 'Helper') {} else {

            $this->check_login(); // TODO

            if (session('ADMIN_TYPE') == '1' || (CONTROLLER_NAME == 'Admin' && ACTION_NAME == 'login') || (CONTROLLER_NAME == 'Admin' && ACTION_NAME == 'loginToSeatManage') || (CONTROLLER_NAME == 'Admin' && ACTION_NAME == 'center') || (CONTROLLER_NAME == 'Admin' && ACTION_NAME == 'manager_top') || (CONTROLLER_NAME == 'Admin' && ACTION_NAME == 'manager_left')) {
            } else {

                $admin_type = session('ADMIN_TYPE');
                // 角色权限控制
                $res = D('Role')->where('role_id=' . $admin_type)->find();
                $ids = $res['role_auth_ids'];

                if (ACTION_NAME == 'index' || ACTION_NAME == 'add' || ACTION_NAME == 'edit' || ACTION_NAME == 'del') {
                    $where1 = " admin_name = 'Admin' AND auth_c = '" . CONTROLLER_NAME . "' AND auth_a IN('index','add','edit','del')";
                    $where = " admin_name = 'Admin' AND auth_id IN ($ids) AND auth_level>=2 AND auth_c = '" . CONTROLLER_NAME . "' AND auth_a IN('index','add','edit','del')";
                } else {
                    $where1 = " admin_name = 'Admin' AND auth_c = '" . CONTROLLER_NAME . "' AND auth_a ='" . ACTION_NAME . "'";
                    $where = " admin_name = 'Admin' AND auth_id IN ($ids) AND auth_level>=2 AND auth_c = '" . CONTROLLER_NAME . "' AND auth_a = '" . ACTION_NAME . "'";
                }
                
            

                $res1 = D('Auth')->where($where1)->select();
                 

                if (!$res1) {
                    $this->error('您访问该页面不存在!', U('Admin/login'));
                }

                $auth = D('Auth')->where($where)->select();

                if (!$auth) {
                    $this->error('您无权访问该页面!', U('Admin/login'));
                }
            }
        }
    }

    function check_login()
    {
        $admin_type = intval(session('ADMIN_TYPE'));
        $admin_id = intval(session('ADMIN_ID'));
        $admin_name = strval(session('ADMIN_NAME'));
        $admin_key = strval(session('ADMIN_KEY'));

        $check_cookie_key = md5($admin_type . $admin_id . $admin_name . self::cookie_key);

        if ($admin_id == 0 || $admin_name == '' || $admin_key != $check_cookie_key) {
            if (CONTROLLER_NAME == 'TicketReport' && ACTION_NAME != 'login') {
                $this->error('<a href="' . U('TicketReport/login') . '">请登录</a>', U('TicketReport/login'));
                exit();
            } else {
                $this->error('<a href="' . U('Admin/login') . '">请登录</a>', U('Admin/login'));
                exit();
            }
        } else {
            $GLOBALS['ADMIN'] = D('Admin')->find($admin_id);
            define('ADMIN_TYPE', $admin_type);
            define('ADMIN_ID', $admin_id);
            define('ADMIN_NAME', $admin_name);
        }
    }

    public function index()
    {     
        $this->_list('');
    }

    public function add()
    {
        if (IS_POST) {

            foreach ($_POST as $k => $v){
                if (is_array($v))
                    $_POST[$k] = implode(",", $v);

            }
            if(CONTROLLER_NAME == 'Hospital' && ACTION_NAME == 'add'){
                $password = trim($_POST['password']);
                if($password==''){
                    $_POST['password'] = md5('123456');
                }else{
                    $_POST['password'] = md5($password);
                }
            }

            $this->insert();
        } else {
            $this->display('form');
        }
    }

    public function edit($id = 0, $ref = '')
    {

        session('edit_ref', $ref);
        
        $id=reset(I());//获取数组第一个 就是id
        
         
        $mod = D(CONTROLLER_NAME);
     
        $vo = $mod->find($id);

        $this->assign('vo', $vo);

        if (IS_POST) {
            foreach ($_POST as $k => $v){
                if (is_array($v))
                    $_POST[$k] = implode(",", $v);

            }

            $this->save();
        } else {
            $this->display('form');
        }
    }

   public function dostate($back = '/index'){
        $id=reset(I());//获取数组第一个 就是id
        $mod = D(CONTROLLER_NAME);
        $where['sy_id']=$id;
        $save['sy_type']=1;
        $vo = $mod->where($where)->save($save);
        $this->success('操作成功', U(CONTROLLER_NAME . $back));
   }

    protected function insert($name = '', $back = '/index')
    {    
        $name = $name ? $name : CONTROLLER_NAME;
        $db = D($name);
        if ($db->create() === false) {
            $this->error($db->getError());
        } else {
            $id = $db->add();
            if ($id) {
                // 记录系统管理员日志
                D('AdminLog')->addLog(array(
                    'controller' => $name,
                    'action' => 'insert',
                    'content' => "执行添加操作,对应的记录id为" . $id
                ));
                $this->success('操作成功', U(CONTROLLER_NAME . $back));
            } else {
                $this->error('操作失败', U(CONTROLLER_NAME . $back));
            }
        }
    }

    protected function save($name = '', $back = '/index')
    {
        $name = $name ? $name : CONTROLLER_NAME;
        $db = D($name);
        if ($db->create() === false) {

            $this->error($db->getError());
        } else {
            $id = $db->save();
            // echo $db->getLastSql();exit;
            if ($id == true) {
                if (session('edit_ref')) {
                    $url = session('edit_ref');
                } else {
                    $url = U(CONTROLLER_NAME . $back);
                }
                // 记录系统管理员日志
                D('AdminLog')->addLog(array(
                    'controller' => $name,
                    'action' => 'save',
                    'content' => "执行更新操作,对方的记录id为" . $id
                ));
                $this->success('操作成功', $url);
            } else {
                $this->error('操作失败', U(CONTROLLER_NAME . $back));
            }
        }
    }

    public function del($id = 0)
    {   
        $id=reset(I());//获取数组第一个 就是id
        $name = $name ? $name : CONTROLLER_NAME;
        $db = D($name);
        if ($db->delete($id)) {
            // 记录系统管理员日志
            D('AdminLog')->addLog(array(
                'controller' => $name,
                'action' => 'del',
                'content' => "执行了删除操作,对应的记录id为" . $id
            ));
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function _list($where,$mod_name='',$pageSize=15)
    {      
        $param=I($_POST);
        //buttonsearch 为button 按钮name值 如果获取到了 则 为点击搜索按钮 操作
        //但是 在翻页的时候 会保留 buttonsearch 值
        //所以 可以判断是翻页 还是  搜索按钮 需要 通过判断 buttonsearch 和 p
        //如果 只有 buttonsearch 则为 搜索 如果 buttonsearch&&p 则为翻页
        $buttonsearch=$param['buttonsearch'];
        $p=isset($param['p']);
        if(!$p&&$buttonsearch){
         $_GET['p']=1;
        }

        if(!empty($param['time_start'])||!empty($param['time_end'])){
                 if(empty($param['time_start'])&&!empty($param['time_end'])){
                    $where[$param['timequantumnorepeat']]=array('lt',strtotime($param['time_end'])); 
                 }elseif(empty($param['time_end'])&&!empty($param['time_start'])){
                    $where[$param['timequantumnorepeat']]=array('gt',strtotime($param['time_start'])); 
                 }else{
                    $where[$param['timequantumnorepeat']]=array('between',array(strtotime($param['time_start']),strtotime($param['time_end'])));  
                 }
            }else{
               // unset($param['timequantumnorepeat']);
            }

       //like查询
        foreach($param as $key=>$value){
            if($value){
              $before= substr($key,0, 1);
              $after = substr($key,-1);
              if($before=='%'&&$after!='%'){
                $keyp=substr($key, 1);
                $where[$keyp]=array('like','%'.trim($value));  
                $this->assign($keyp,trim($value)); 
              }elseif($before!='%'&&$after=='%'){
                $keyp = substr($key, 0,-1);
                $where[$keyp]=array('like',trim($value).'%'); 
                $this->assign($keyp,trim($value)); 
              }elseif($before=='%'&&$after=='%'){
                $keyp=substr(substr($key, 1),0, -1);
                $where[$keyp]=array('like','%'.trim($value).'%'); 
                $this->assign($keyp,trim($value)); 
              }else{
                $where[$key]=trim($value); 
                $this->assign($key,trim($value)); 
              }
            }  
        }

        //获取此表自增长id
        $primaryfileinfo=get_add_id(CONTROLLER_NAME); 
  
        
        if ($mod_name=='') {
            $mod = D(CONTROLLER_NAME);
        } else {
            $mod = D($mod_name);
        }
          
        if (in_array('ord', $mod->getDbFields())) {
            $order = 'ord DESC ,id DESC';
        } else {
            $order = $primaryfileinfo[0]['column_name'].' DESC';
        }
        import('ORG.Util.Page');
        $count = $mod->where($where)->count(); // 查询满足要求的总记录数
        $Page = new \Think\Page($count); // 实例化分页类 传入总记录数
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $Page->parameter = array_map('urlencode', get_page_param($map));
        $nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
        
        
  
        $list = $mod->where($where)
            ->order($order)
            ->page($nowPage . ',' . $Page->listRows)
            ->select();
        


         foreach ($list as $key => $value) {
             $list[$key]['primaryfileinfo']=$primaryfileinfo[0]['column_name'];
         }
       

       
        $show = $Page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $list); // 赋值数据集
        $this->display(); // 输出模板
        return $list;
    }

    public function _list2($where,$order='')
    {
        $mod = D(CONTROLLER_NAME);
        if($order == ''){
            if (in_array('id', $mod->getDbFields())) {
                $order = 'id DESC';
            } else {
                $order = 'add_time DESC';
            }
        }
        import('ORG.Util.Page');
        $count = $mod->where($where)->count(); // 查询满足要求的总记录数
        $Page = new \Think\Page($count); // 实例化分页类 传入总记录数
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $Page->parameter = array_map('urlencode', get_page_param($map));
        $nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
        $list = $mod->where($where)
            ->order($order)
            ->page($nowPage . ',' . $Page->listRows)
            ->select();
        $show = $Page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $list); // 赋值数据集
        $this->display(); // 输出模板
        return $list;
    }

    function _select($m, $name = 'name', $where = '', $default = '')
    {
        $ret = array();
        if ($default != '')
            $ret[0] = $default;
        $ary = D($m)->where($where)->select(); // ->cache("$m_$name_$where_$default",0)
        foreach ($ary as $k) {
            $ret[$k['id']] = $k[$name];
        }
        return $ret;
    }

    public function get_list($model_name, $where = "", $ord = "")
    {
        $mod = D($model_name);

        if ($order == "") {
            if (in_array('ord', $mod->getDbFields())) {
                $order = 'ord DESC';
            } else {
                $order = 'id DESC';
            }
        }
        import('ORG.Util.Page');
        $count = $mod->where($where)->count(); // 查询满足要求的总记录数
        $Page = new \Think\Page($count, 10); // 实例化分页类 传入总记录数
        $Page->parameter = array_map('urlencode', get_page_param($map)); // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $nowPage = isset($_GET['p']) ? $_GET['p'] : 1;
        $list = $mod->where($where)
            ->order($order)
            ->page($nowPage . ',' . $Page->listRows)
            ->select();
        $show = $Page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $list); // 赋值数据集
        $is_last_page = $nowPage >= $Page->totalPages ? true : false;
        $ret['page'] = $show;
        $ret['list'] = $list;
        $ret['is_last_page'] = $is_last_page;
        return $ret;
    }
}
